// 在组件中使用

import request from "@/utils/request.js";
import {TokenService} from "@/stores/userStore.js";
import {ElMessage} from "element-plus";
import {console} from "vuedraggable/src/util/helper.js";

export async function login(username, password) {
  return new Promise((resolve, reject) => {
    request.post("login", {
      username,
      password,
    }).then(res => {
      const result = res.data;
      const data = result.data;
      console.log(result)
      if (result.status == "success") {
        TokenService.setUserAuth(data.user_id, data.access_token);
        console.log("登录成功")
        resolve({success: true, message: result.message});
      } else {
        reject({success: false, message: result.message});
      }
    }).catch((error) => {
      console.log(error);
      if (error.response && error.response.data) {
        reject({success: false, message: error.response.data.message});
      } else {
        reject({success: false, message: 'Network error'});
      }
    })
  })
}

export async function register(username, password, email) {
  return new Promise((resolve, reject) => {
    request.post("register", {
      username,
      password,
      email,
    }).then(res => {
      const result = res.data;
      console.log(result);
      if (result.status == "success") {
        console.log("注册成功");
        resolve({success: true, message: result.message});
      } else {
        reject({success: false, message: result.message});
      }
    }).catch((error) => {
      if (error.response && error.response.data) {
        reject({success: false, message: error.response.data.message});
      } else {
        reject({success: false, message: 'Network error'});
      }
    });
  });
}

export async function forgetPassword(username, email) {
  return new Promise((resolve, reject) => {
    request.post("forget_password", {
      username,
      email,
    }).then(res => {
      const result = res.data;
      console.log(result);
      if (result.status == "success") {
        console.log("找回密码请求成功");
        resolve({success: true, message: result.message});
      } else {
        reject({success: false, message: result.message});
      }
    }).catch((error) => {
      if (error.response && error.response.data) {
        reject({success: false, message: error.response.data.message});
      } else {
        reject({success: false, message: 'Network error'});
      }
    });
  });
}

export async function generateStudyPlan(user_id, subject, goal, duration) {

  return new Promise((resolve, reject) => {
    request.post('/generate_study_plan', {
      user_id,
      subject,
      goal,
      duration
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("生成学习计划成功");
          resolve({success: true, message: result.message, plan: result.data.plan});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}

export async function getHistory(user_id) {
  return new Promise((resolve, reject) => {
    request.post('/chat/histories', {
      user_id,
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("获取历史记录成功");
          resolve({success: true, message: result.message, chat_sessions: result.data.chat_sessions});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}

export async function startChat(user_id) {
  return new Promise((resolve, reject) => {
    request.post('/chat/start_chat', {
      user_id,
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("开始聊天成功");
          console.log(result);
          resolve({success: true, message: result.message, chat_id: result.data.chat_session_id});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}

export async function deleteChatSession(chat_session_id) {
  return new Promise((resolve, reject) => {
    request.post('/chat/delete_chat', {
      chat_session_id,
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("删除成功");
          resolve({success: true, message: result.message});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}

export async function Chat(user_id,chat_session_id, question) {
  return new Promise((resolve, reject) => {
    request.post('/chat/chat', {
      user_id,
      chat_session_id,
      question
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("开始聊天");
          resolve({success: true, message: result.message, response: result.data.response});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}


export async function translateText(user_id, source_language, target_language, original_text) {
  return new Promise((resolve, reject) => {
    request.post('/translate/translate', {
      user_id,
      source_language,
      target_language,
      original_text
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("翻译请求成功");
          resolve({success: true, message: result.message, translated_text: result.data.translated_text});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}


export async function getAllNotes(user_id) {
  return new Promise((resolve, reject) => {
    request.post('note/get_all', {
      user_id,
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("请求所有笔记成功");
          resolve({success: true, message: result.message, notes: result.data.notes});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}


export async function saveNote(user_id, note_id, title, content, summary) {
  return new Promise((resolve, reject) => {
    request.post('note/save', {
      user_id, note_id, title, content, summary
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("保存成功");
          resolve({success: true, message: result.message, summary: result.data.summary});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          console.log(error)
          reject({success: false, message: 'Network error'});
        }
      });
  });
}


export async function deleteNote(note_id) {
  return new Promise((resolve, reject) => {
    request.post('note/delete', {
      note_id,
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("删除笔记成功");
          resolve({success: true, message: result.message, data: null});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}


export async function generateSummary(content) {
  return new Promise((resolve, reject) => {
    request.post('note/generate', {
      content
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("生成摘要成功");
          resolve({success: true, message: result.message, summary: result.data.summary});
        } else {
          reject({success: false, message: result.message});
        }
      })
      .catch(error => {
        if (error.response && error.response.data) {
          reject({success: false, message: error.response.data.message});
        } else {
          reject({success: false, message: 'Network error'});
        }
      });
  });
}

export async function getUserConfig(user_id) {
  return new Promise((resolve, reject) => {
    request.post('user_config', {
      user_id,
    })
      .then(response => {
        const result = response.data;
        console.log(result);
        if (result.status === 'success') {
          console.log("请求用户信息成功");
          resolve({success: true, message: result.message, data: result.data});
        }
      })
  })
}

export const updateUserConfig = async (user_id, gender, bio, location, birth_date, avatar) => {
  return new Promise((resolve, reject) => {
    request.post('user_configs', {
      user_id, // 保持与后端一致
      gender,
      bio,
      location,
      birth_date,
      avatar // 确保头像 URL 也能更新
    }).then(res => {
      if (res.data.status === 'success') {
        resolve({success: true, message: res.data.message});
      } else {
        reject({success: false, message: res.data.message});
      }
    }).catch(error => {
      if (error.response && error.response.data) {
        reject({success: false, message: error.response.data.message});
      } else {
        reject({success: false, message: 'Network error'});
      }
    })
  })
}

export const uploadAvatar = (file) => {
  return new Promise((resolve, reject) => {
    const formData = new FormData();
    formData.append('avatar', file);
    request.post('user/upload_avatar', formData).then(res => {
      if (res.data.status === 'success') {
        resolve({ success: true, avatar_url: res.data.avatar_url });
      } else {
        reject({ success: false, message: res.data.message });
      }
    }).catch(error => {
      if (error.response && error.response.data) {
        reject({ success: false, message: error.response.data.message });
      } else {
        reject({ success: false, message: 'Network error' });
      }
    });
  });
};
